package cn.webestar.scms.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zgs
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityAutoConfig {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private SecurityProperties properties;

    @Bean
    @ConditionalOnMissingBean
    public PasswordEncoder passwordEncoder() {
        String encodingId = "bcrypt";
        Map<String, PasswordEncoder> encoders = new HashMap<>(8);
        encoders.put(encodingId, new BCryptPasswordEncoder());
        log.info("[security-spring-boot-starter]:Init PasswordEncoder");
        return new DelegatingPasswordEncoder(encodingId, encoders);
    }

    @Bean
    @ConditionalOnProperty(prefix = "scms.security", name = "enable", havingValue = "true")
    public FilterRegistrationBean<SessionFilter> authFilterRegister() {
        FilterRegistrationBean<SessionFilter> registration = new FilterRegistrationBean<>();
        registration.setOrder(1000);
        registration.setFilter(new SessionFilter(redisTemplate, properties));
        registration.setName("authFilter");
        registration.addUrlPatterns(properties.getUrlPatterns());
        log.info("[security-spring-boot-starter]:Register SessionFilter,url={}", properties.getUrlPatterns());
        return registration;
    }

}
